package com.zmx.piglearn

import android.os.AsyncTask
import android.widget.ProgressBar
import android.widget.TextView

class MyAsyncTask(val txt: TextView, val pgBar: ProgressBar) : AsyncTask<Int, Int, String>() {

    class DelayOperator {
        // 延时操作, 用来模拟下载
        fun delay() {
            try {
                Thread.sleep(1000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }
    }

    // 不在 UI 线程中
    // 通过调用publishProgress()方法
    // 触发onProgressUpdate对UI进行操作
    override fun doInBackground(vararg params: Int?): String {
        val dop = DelayOperator()
        var i = 10
        while (i <= 100) {
            dop.delay()
            publishProgress(i)
            i += 10
        }
        return (i + (params[0] ?: 0)).toString()
    }

    // 运行在 UI 线程中
    override fun onPreExecute() {
        txt.text = "开始执行异步线程~"
    }

    // 运行在 UI 线程中
    override fun onProgressUpdate(vararg values: Int?) {
        val value = values[0]
        pgBar.progress = value ?: 0
    }
}